import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

# 导入数据
data = pd.read_excel('第二章 图表(前15).xlsx',sheet_name='4 标注柱形图',usecols='B:C',skiprows=1)

# 创建图形和坐标轴
fig, ax = plt.subplots(figsize=(8, 6))

# 设置背景颜色
fig.patch.set_facecolor('#00002d')
ax.set_facecolor('#00002d')

# 设置X轴和Y轴数据
x = np.arange(len(data['月份']))  # X轴位置
y = data['销量']  # Y轴高度

# 绘制不同颜色的柱形图
bars = ax.bar(x, y, color=['red','navy','royalblue','green','teal','blue','purple','slateblue'])

# 设置X轴标签
ax.set_xticks(x)
ax.set_xticklabels(data['月份'], color='w')

# 设置Y轴标签颜色为白色
ax.set_yticks(ax.get_yticks())
ax.set_yticklabels(ax.get_yticks(), color='w')

# 添加网格线
ax.grid(True, axis='y' ,linestyle='--', linewidth=0.5, color='w')

# 隐藏边框
for spine in ax.spines.values():
    spine.set_visible(False)

# 输出每个柱子的值
colors=['red','navy','royalblue','green','teal','blue','purple','slateblue']
for i in range(len(x)):
    facecolor = colors[i]
    ax.text(x[i], y[i]+300, f'{int(y[i])}', ha='center', color='w', fontsize=10, bbox=dict(facecolor=facecolor, boxstyle='round'))

# 调整图形位置
plt.subplots_adjust(top=0.8)  # 留出空间给标题

# 添加标题
plt.text(0, 1.15, '2021年商品销量情况', color='w', fontsize=24, transform=ax.transAxes)
plt.text(0, 1.05, '口红销量最好达9221，是眼影最低值2645近3.5倍', color='w', fontsize=16, transform=ax.transAxes)

# 导出图片
#plt.savefig('D:/python charm/01/可视化/第二章前15/图片/标注柱形图.png', dpi=300, bbox_inches='tight', facecolor='#00002d')

# 显示图形
plt.show()